package com.itheima.controller;

import com.itheima.dto.ChangePasswordDTO;
import com.itheima.dto.UserLoginDTO;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@RequestBody UserLoginDTO userLoginDTO) {
        return ResponseEntity.ok(userService.registerUser(userLoginDTO));
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> loginUser(@RequestBody UserLoginDTO loginDTO) {
        Map<String, String> result = userService.loginUser(loginDTO);
        if (result.containsKey("token")) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.status(401).body(result);
    }

    // 修改密码
    @PutMapping("/change")
    public ResponseEntity<String> changePassword(
            @RequestBody ChangePasswordDTO changePasswordDTO,
            @RequestHeader("Authorization") String token) {

        // 从 Authorization 头中获取 Token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
            System.out.println(token);// 去掉 "Bearer " 前缀
        }

        // 调用 service 层修改密码
        String result = userService.changePassword(token, changePasswordDTO);
        return ResponseEntity.ok(result);
    }

    // 用户登出
    @PostMapping("/logout")
    public ResponseEntity<String> logout(@RequestHeader("Authorization") String token) {
        // 从 Authorization 头中获取 Token
        if (token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
        }

        // 调用 service 层执行登出逻辑
        userService.logout(token);
        return ResponseEntity.ok("Logged out successfully");
    }
}